using System;
using System.Diagnostics.Contracts;
using System.Linq;

namespace ReactiveCode.Util
{
    class WeakReference<T>
        where T : class
    {
        WeakReference _ref;

        [ContractInvariantMethod]
        void ObjectInvariant()
        {
            Contract.Invariant(IsAlive == (Target != null));
        }

        public WeakReference(T target, bool trackResurrection = false)
        {
            Contract.Requires(target != null);
            _ref = new WeakReference(target, trackResurrection);
        }

        public bool TrackResurrection
        {
            get { return _ref.TrackResurrection; }
        }

        public T Target
        {
            [Pure]
            get
            {
                return _ref.Target as T;
            }
        }

        public bool IsAlive
        {
            [Pure]
            get { return _ref.IsAlive; }
        }
    }
}